package cloud.uke.jds.api;

import cloud.uke.jds.api.internal.InternalStoreDataHandler;
import java.util.Objects;
import java.util.regex.Pattern;
import lombok.Data;

/** @author du */
/**
 * DataSyncBuilder class.
 *
 * @author du
 * @version $Id: $Id
 */
@Data
public class DataSyncBuilder<T, ID> {
  private static final Pattern pattern = Pattern.compile("(^[a-zA-Z]+[a-zA-Z0-9_]*$){1,24}");
  /** （异常，无数据）等待时间 */
  long waitMills = 3000;
  /**
   * 数据来源标识符，用来区分不同数据
   *
   * <p>比如 dbA
   */
  String srcId;
  /**
   * 同步目标标识符，用来记录同步状态
   *
   * <p>比如 mysql2
   */
  String targetId;

  /**
   * 同步完成后是否删除该记录，默认false
   *
   * <p>注意：如果有多个同步目标，不要启用此功能 TODO 所有目标同步完成后，除该记录
   */
  boolean autoDelete;

  InternalStoreDataHandler<T, ID> internalStoreDataHandler;
  UserDataHandler<T, ID> userDataHandler;

  /**
   * build.
   *
   * @return a {@link cloud.uke.jds.api.DataSync} object
   */
  public DataSync<T, ID> build() {
    checkArgs();
    internalStoreDataHandler.setFlags(srcId, targetId);
    internalStoreDataHandler.setDataSyncBuilder(this);
    return new DataSync<>(this);
  }

  private void checkArgs() {
    Objects.requireNonNull(this.srcId, "srcId is required");
    Objects.requireNonNull(this.targetId, "targetId is required");
    Objects.requireNonNull(this.internalStoreDataHandler, "wrapDataHandler is required");
    Objects.requireNonNull(this.userDataHandler, "dataTransfer is required");

    if (!pattern.matcher(this.srcId).matches()) {
      throw new IllegalArgumentException(
          "srcId is not valid, only support [start with char, max len 24]");
    }

    if (!pattern.matcher(this.targetId).matches()) {
      throw new IllegalArgumentException(
          "targetId is not valid, only support [start with char, max len 24]");
    }
  }
}
